import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { FormInstance } from 'antd/lib/form';
import { Modal, Button, message, Input, Form } from 'antd';
import { specicalChars, styleRequired } from '../../../support/constant/common.js';
import { encryptedData } from '@/utils/utils';
import { publicKey } from "../../../../public/global";
import { validateContinuousChar } from '@/utils/validator';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
    account: state.account,
    menu: state.menu,
    loading: state.loading.effects['account/postObjWithRes'],
});
class ResetPwdModal extends PureComponent<any, any> {

    formRef = React.createRef<FormInstance>();

    constructor(props: any) {
        super(props);
        this.state = {
            sid: null
        };
    }

    componentDidMount() {

    }

    componentDidUpdate() {
        const { record } = this.props;
        if (record) {
            this.setState({ sid: record.sid });
        }
    }

    getLabel = (lable: any) => <span><span style={styleRequired}>* </span>{lable}</span>;

    ok = (values: any) => {
        const { dispatch, formValues, pageObj } = this.props;
        const { sid } = this.state;
        // 密码使用RSA加密
        const accountPwd = encryptedData(values.accountPwd, publicKey); 
        const obj = {
            currentPwd: accountPwd,
            sid: sid
        };
        dispatch({
            type: 'account/postObjWithRes',
            payload: {
                url: '/account/resetpwd',
                ...obj
            },
            callback: (response: any) => {
                if (response.statusCode === '0') {
                    let params = { ...formValues, page: pageObj.current, size: pageObj.pageSize }
                    this.close();
                    message.success('操作成功');
                    dispatch({
                        type: "account/postFetchPage",
                        payload: { url: "/account/findbypage", ...params }
                    })
                }
            }
        })
    };

    close = () => {
        const { closeModal } = this.props;
        closeModal();
        this.formRef.current?.resetFields();
    }

    submitSave = () => {
        this.formRef.current?.submit();
    }

    checkPwd = (rule: any, value: any) => {

        const { menu: { pwdStrategy: { pwdStrategy, pwdStrategyDesc } } } = this.props;
        if (value) {
            const regex = new RegExp(pwdStrategy);
            if (!regex.test(value)) {
                return Promise.reject(`请输入正确的密码，${pwdStrategyDesc}`);
            } else if(/([\dA-Za-z])\1{3,}/.test(value)) {
                return Promise.reject('禁止密码设置4位连续相同的字符');
            } else if(validateContinuousChar(value)) {
                return Promise.reject('禁止密码设置4位连续递增，递减的数字或字母');
            } else if(specicalChars.some(char => value.toLowerCase().indexOf(char.toLowerCase()) > -1 )) {
                return Promise.reject('禁止密码设置4位1qaz，2wsx，3edc，dfm，admin，dftc，dfrd等简单字符');
            }
        } else {
            return Promise.reject('请输入密码');
        }
        return Promise.resolve();
    }

    render() {
        const { modalVisible, loading } = this.props;
        const footer = (
            <div>
                <Button size="small" onClick={this.close}>取消</Button>
                <Button size="small" loading={loading} onClick={this.submitSave} type="primary">保存</Button>
            </div>
        );
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 12 },
                md: { span: 16 },
            },
        };
        return (
            <Modal
                style={{ top: 20 }}
                footer={footer}
                title="重置密码"
                visible={modalVisible}
                onCancel={this.close}
            >
                <Form
                    style={{ marginTop: 12 }}
                    ref={this.formRef}
                    onFinish={this.ok}
                >
                    <FormItem
                        {...formItemLayout}
                        label={this.getLabel("密码")}
                        name="accountPwd"
                        hasFeedback
                        rules={[{ validator: this.checkPwd }]}
                    >
                        <Input.Password maxLength={50} placeholder="请输入密码" />
                    </FormItem>
                </Form>
            </Modal>
        );
    }
}
export default connect(mapStateToProps)(ResetPwdModal);